package newcall.com.newcalldemo;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.m800.m800demo.R;
import com.m800.verification.M800PhoneVerifiedResult;
import com.m800.verification.M800VerificationClient;
import com.m800.verification.M800VerificationManager;
import com.m800.verification.M800VerificationManagerCallback;
import com.m800.verification.M800VerificationType;

import java.util.Locale;

public class VerificationCodeActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String DEBUG_TAG = VerificationCodeActivity.class.getSimpleName();

    public static final String EXTRA_CODE_LENGTH = "expectedCodeLength";
    public static final String EXTRA_REQUEST_ID = "requestID";
    public static final int RESULT_ERROR = 1001;

    private static final int RESEND_INTERVAL_SEC = 60;
    private static final int DEFAULT_CODE_LENGTH = 6;

    private EditText mCodeEditText;
    private Button mResendButton;
    private Button mSubmitButton;

    private M800VerificationManager mVerificationManager;
    private int mExpectedInputLength;
    private CountDownTimer mResendTimer;
    private String mInput;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_verification_code_activity);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("Enter the verification code from other device to proceed multiple login.");
        }

        // Set up verification manager
        mVerificationManager = M800VerificationClient.getVerificationManager(getApplicationContext());
        mVerificationManager.addCallback(mVerificationManagerCallback);

        if (getIntent() != null) {
            mExpectedInputLength = getIntent().getIntExtra(EXTRA_CODE_LENGTH, DEFAULT_CODE_LENGTH);
        }

        mCodeEditText = (EditText) findViewById(R.id.et_verification_code);
        mSubmitButton = (Button) findViewById(R.id.btn_submit);
        mResendButton = (Button) findViewById(R.id.btn_resend);

        applyInputLengthLimitation();
        mCodeEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {
                mInput = mCodeEditText.getText().toString().trim();
                mSubmitButton.setEnabled(mInput.length() >= mExpectedInputLength);
            }
            @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
            @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
        });
        mSubmitButton.setOnClickListener(this);
        mResendButton.setOnClickListener(this);
        mResendButton.setEnabled(false);
        mResendTimer = new ResendTimer();
        mResendTimer.start();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.btn_submit:
                mSubmitButton.setEnabled(false);
                mVerificationManager.verifySmsCode(mInput);
                break;
            case R.id.btn_resend:
                mResendButton.setEnabled(false);
                mVerificationManager.requestResendCode();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVerificationManager.removeCallback(mVerificationManagerCallback);
        mResendTimer.cancel();
    }

    private void applyInputLengthLimitation() {
        if (mExpectedInputLength > 0) {
            mCodeEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mExpectedInputLength)});
        }
    }

    private M800VerificationManagerCallback mVerificationManagerCallback = new M800VerificationManagerCallback() {

        @Override
        public void onCodeCheckedIncorrect(String code) {
            Log.e(DEBUG_TAG, "onCodeCheckedIncorrect  code = " + code);
            Toast.makeText(VerificationCodeActivity.this,
                    "The input code is not correct!", Toast.LENGTH_LONG).show();
            mSubmitButton.setEnabled(true);
        }

        @Override
        public void onWaitingToReceiveCode(int codeLength) {
            Log.d(DEBUG_TAG, "onWaitingToReceiveCode  codeLength = " + codeLength);
            mExpectedInputLength = codeLength;
            applyInputLengthLimitation();

            // Restart the timer
            mResendTimer = new ResendTimer();
            mResendTimer.start();
        }

        @Override
        public void onSuccess(M800VerificationType type, String requestId) {
            Log.d(DEBUG_TAG, "Code verification success!");
            M800PhoneVerifiedResult m800PhoneVerifiedResult = mVerificationManager.getLastPhoneVerifiedResult();
            Log.d(DEBUG_TAG, "<Verification.onSuccess> requestId = " + m800PhoneVerifiedResult.getRequestId()
                    + " time:" + m800PhoneVerifiedResult.getVerifiedTime());
            Intent result = new Intent();
            result.putExtra(EXTRA_REQUEST_ID, requestId);
            setResult(RESULT_OK, result);
            finish();

            // Log
//            AnswersUtil.logEvent(AnswersUtil.EVENT_PHONE_VERIFICATION, type.name(), true, 0, null);
        }

        @Override
        public void onError(M800VerificationType type, int errorCode, String errorMessage) {
            Log.d(DEBUG_TAG, "Code verification failed, error: " + errorMessage);
            Toast.makeText(VerificationCodeActivity.this, errorMessage, Toast.LENGTH_LONG).show();
            setResult(RESULT_ERROR);
            finish();

//            // Log
//            AnswersUtil.logEvent(AnswersUtil.EVENT_PHONE_VERIFICATION,
//                    type.name(), false, errorCode, errorMessage);
        }
    };

    private class ResendTimer extends CountDownTimer {

        private ResendTimer() {
            super(RESEND_INTERVAL_SEC * 1000, 1000);
        }

        @Override
        public void onTick(long l) {
            int sec = (int) ((l / 1000) % 60);
            int min = (int) (l / 1000 / 60);
            String text ="Resend Message"
                    + String.format(Locale.getDefault(), " (%02d:%02d)", min, sec);
            mResendButton.setText(text);
        }

        @Override
        public void onFinish() {
            mResendButton.setText("Resend Message");
            mResendButton.setEnabled(true);
        }
    }
}
